package pgself

import (
	"crypto/md5"
	"database/sql"
	"errors"
	"fmt"

	"gitee.com/tinkler/yunfei/self"
	"gitee.com/tinkler/yunfei/self/register"
)

func init() {
	driver := Driver{}
	self.Register("pgself", &driver)
}

// Driver pgself driver
type Driver struct{}

// VerifyUser verify user by id
func (d Driver) VerifyUser(db *sql.DB, user interface{}) error {
	u, ok := user.(register.StandarUser)
	if !ok {
		panic("self:verify user is not ok")
	}
	qs := `
	SELECT name,
		email,
		password
		FROM user
		WHERE id = $1
	`
	var password string
	var email string
	row := db.QueryRow(qs, u.ID)
	err := row.Scan(
		&u.Name,
		&email,
		&password,
		&u.Rolename,
	)
	if err != nil {
		return fmt.Errorf("%s: id:%d, name:%s", err.Error(), u.ID, u.Name)
	}

	hash := md5.New()
	hash.Write([]byte(email + u.Password))
	hashCode := fmt.Sprintf("%x", md5.Sum(nil))
	if hashCode == password {
		return nil
	}
	return errors.New("密码不匹配")
}
